package com.youku.mson;

import com.youku.mson.lexer.Lexer;
import com.youku.mson.parser.JsonParser;
import com.youku.mson.serializer.JsonSerializer;
import com.youku.mson.serializer.JsonSerializerFactory;
import com.youku.mson.serializer.JsonWriter;
import com.youku.mson.type.JsonValue;
import com.youku.mson.util.TypeAdapter;

public class Mson {

	public <T> T fromJson(String json, Class<T> targetClass) {
		JsonValue jsonValue = convert2JsonValue(json);
		return fromJson(jsonValue, targetClass);
	}

	private JsonValue convert2JsonValue(String json) {
		Lexer lexer = new Lexer(json);
		lexer.parse();
		JsonParser parser = new JsonParser(lexer);
		return parser.parse();
	}

	@SuppressWarnings("unchecked")
	private <T> T fromJson(JsonValue value, Class<T> targetClass) {
		return (T) value.read(new TypeAdapter(targetClass));
	}

	public String toJson(Object target) {
		JsonWriter out = new JsonWriter();
		JsonSerializer serializer = JsonSerializerFactory.getSerializer(target.getClass());
		serializer.serialize(out, target);
		return out.toString();
	}
}
